package com.hwd.srb.core.util;

import com.hwd.srb.common.exception.BusinessException;
import com.hwd.srb.core.util.adapter.*;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄伟东/Victor
 * @date 2022/3/31 23:03
 * @Description
 */
@Component
public class AmountHelperDispatch {

    public List<AmountHelperAdapter> amountHelperAdapters = new ArrayList<>();

    public AmountHelperMapping amountHelperMapping = new AmountHelperMapping();

    public AmountHelperDispatch() {
        amountHelperAdapters.add(new Amount1HelperAdapter());
        amountHelperAdapters.add(new Amount2HelperAdapter());
        amountHelperAdapters.add(new Amount3HelperAdapter());
        amountHelperAdapters.add(new Amount4HelperAdapter());

        amountHelperMapping.initHelperMethods();
    }

    public void doDispatch(BigDecimal invest, BigDecimal yearRate, int totalMonth, String returnMethod) {

        // 通过还款方式，找到对应的利息计算工具
        AmountHelper amountHelper = getAmountHelper(returnMethod);

        // 通过利息计算工具找到对应的适配器
        AmountHelperAdapter amountHelperAdapter = getAmountHelperAdapter(amountHelper);

        // 通过适配器执行对应计算工具的方法
        BigDecimal interestCount = amountHelperAdapter.getInterestCount(invest, yearRate, totalMonth);
        System.out.println("interestCount = " + interestCount);


    }

    public static void main(String[] args) {
        new AmountHelperDispatch().doDispatch(
                new BigDecimal("30000"),
                new BigDecimal("0.12"),
                3,
                "等额本息");
    }

    public AmountHelper getAmountHelper(String returnMethod) {
        if (this.amountHelperMapping != null) {
            return amountHelperMapping.getAmountHelper(returnMethod);
        }
        return null;
    }

    public AmountHelperAdapter getAmountHelperAdapter(Object amountHelper) {
        if (this.amountHelperAdapters != null) {
            for (AmountHelperAdapter adapter : this.amountHelperAdapters) {
                if (adapter.supports(amountHelper)) {
                    return adapter;
                }
            }
        }
        throw new BusinessException("No adapter for amountHelper [" + amountHelper +
                "]: The AmountHelperDispatch configuration needs to include a AmountHelperAdapter that supports this " +
                "amountHelper");
    }

}
